<template>
  <el-form-item v-if="!authors.length" label="作者">
    <span class="unselect-author">未选择作者</span>
    <add-author-component v-model="authors"/>
  </el-form-item>
  <el-form-item v-else :label="'作者'+(doc?.doi?'【对作者的修改会实时更新】':'')">
    <div style="display: flex;flex-wrap: wrap">
      <span v-for="(it,i) in authors" :key="i" @mouseover="changeFlag(i,true)" @mouseleave="changeFlag(i,false)" class="author-desc-line">
        <span>{{ i + 1 }}. </span>
        <span class="show-author-detail" @click="showAuthorDetail(i)">{{ it.lastName + it.firstName }}</span>
        <span class="del-author" v-if="flag[i]===true" @click="delAuthor(i)">×</span>
      </span>
      <add-author-component v-model="authors"/>
    </div>
  </el-form-item>
  <author-show-dialog-component/>
  <hr>
</template>

<script setup>
import AddAuthorComponent from "@/components/add/document/author/AddAuthorComponent.vue";
import {defineModel, inject} from "vue";
import {delDocAuthorApi} from "@/apis/author";
import {provide, ref} from "vue";
import AuthorShowDialogComponent from "@/components/add/document/author/AuthorShowDialogComponent.vue";

const authors = defineModel()

const {has} = defineProps(['has'])

const authorDetail = has ? inject('showAuthor') : ref({}) /*待展示的作者*/
const authorShowDialog = has ? inject('authorShowDialog') : ref(false)

if (!has) {
  // 如果父级组件没有provide，那么我来provide，确保只有一个provide
  provide('showAuthor', authorDetail)
  provide('authorShowDialog', authorShowDialog)
}

const showAuthorDetail = (j) => {
  const len = authors.value.length
  if (0 <= j && j < len) {
    authorDetail.value = authors.value[j]
    showAuthorDesc()
  }
}

const showAuthorDesc = () => {
  authorShowDialog.value = true
}


const flag = ref([])
const changeFlag = (i, v) => {
  flag.value[i] = v;
}

const doc = inject('doc')

const delAuthor = (j) => {
  const len = authors.value.length
  if (0 <= j && j < len && confirm('确定要删除作者【' + authors.value[j].lastName + authors.value[j].firstName + '】?')) {
    if (doc?.value?.id) {
      delDocAuthorApi(doc.value.id, authors.value[j].id)
    }
    authors.value.splice(j, 1);
  }
}


</script>

<style scoped>
.unselect-author {
  color: red;
  font-style: italic;
  font-weight: bold;
  margin: auto;
  font-size: 16px;
}

.author-desc-line {
  width: 100px;
  height: 35px;
  text-align: left;
  align-items: center;
}

.show-author-detail {
  color: blue;
  font-weight: bold;
}

.show-author-detail:hover {
  cursor: pointer;
  color: darkblue;
  text-align: left;
  font-weight: bold;
}

.del-author {
  width: 20px;
  height: 100%;
  margin-left: 5px;
  font-size: 18px;
}

.del-author:hover {
  font-weight: bold;
  color: red;
  cursor: pointer;
}
</style>